//
//  LCSceneViewController.swift
//  mggz
//
//  Created by QinWei on 2018/1/4.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import Moya
import ObjectMapper
import Kingfisher
import SVProgressHUD
class LCSceneViewController: UIViewController {
    var selectedProject : LCProjectListModel?
    var workerModel : LCMWPersonInfo?
    var refresh:BooleanClick?
    
    //var locationService = BMKLocationService()
    var selectCalloutView : LCCalloutView?
    var inRange:Double?
    
    var mapZoom:Float = 19
    
    
    @IBOutlet weak var warnNum: UILabel!
    @IBOutlet weak var jbbtn: UIButton!
    @IBOutlet weak var jbview: UIView!
    @IBOutlet weak var refreshBtn: UIButton!
    var zoomValue : Float?
    @IBOutlet weak var stepView: UIView!
    
    @IBOutlet weak var addButton: UIButton!
    
    @IBOutlet weak var reduceButton: UIButton!
    lazy var itemArray : [MWCurrentLocationModel] = [MWCurrentLocationModel]()
    lazy var warnDwArray:[MWCurrentLocationModel] = [MWCurrentLocationModel]()
    lazy var warnQQArray:[MWCurrentLocationModel] = [MWCurrentLocationModel]()
    lazy var workInforArray : [LCMWPersonInfo] = [LCMWPersonInfo]()
    lazy var selectModelArray:[MWCurrentLocationModel] = [MWCurrentLocationModel]()
    var selectmodel:MWCurrentLocationModel?
    lazy var pointlist = [CLLocationCoordinate2D]()
    var companyAnnotation : BMKPointAnnotation?
    var mapDetail:MapDetail?
    fileprivate var locationService : BMKLocationService?
    fileprivate lazy var mapView : BMKMapView = {
       let mapView = BMKMapView()
        mapView.frame = CGRect(x: 0, y: 40, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-104)
       let param = BMKLocationViewDisplayParam()
       param.isAccuracyCircleShow = false
        param.locationViewOffsetX = 0
        param.isRotateAngleValid = false
        param.locationViewImgName = "民工位置"
        mapView.updateLocationView(with: param)
        //mapView.addCo
//        mapView.zoomLevel = 17
//        mapView.showMapScaleBar = true
//        mapView.showsUserLocation = true
        return mapView
    }()
    
    
    
    
    //系统方法
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        mapView.viewWillAppear()
        locationService?.delegate = self
        mapView.delegate = self
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        locationService?.delegate = nil
        mapView.delegate = nil
        mapView.viewWillDisappear()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.mapDetail = MapDetail(frame: CGRect.zero)
        self.stepView.backgroundColor = UIColor.white
        self.stepView.layer.borderWidth = 5
        self.stepView.layer.borderColor = UIColor.black.cgColor
        self.stepView.layer.cornerRadius = 2
        self.view.addSubview(mapView)
        self.view.addSubview(self.mapDetail!)
        
        /*self.warnNum.layer.shadowOpacity = 0.5
        self.warnNum.layer.shadowColor = UIColor.gray.cgColor
        self.warnNum.layer.shadowRadius = 2
        self.warnNum.layer.shadowOffset = CGSize(width: 1, height: 1)
        self.warnNum.layer.cornerRadius = 12*/
        self.warnNum.backgroundColor = UIColor.white
        self.warnNum.layer.cornerRadius=10;
//        self.warnNum.layer.shadowColor=UIColor.gray.cgColor
//        self.warnNum.layer.shadowOffset=CGSize(width: 1, height: 1)
//        self.warnNum.layer.shadowOpacity=0.5;
//        self.warnNum.layer.shadowRadius=2;
        self.warnNum.layer.borderWidth = 0.2
        self.warnNum.layer.borderColor = UIColor.init(white: 0.4, alpha: 1).cgColor
        self.warnNum.layer.masksToBounds = true
        
        //self.jbview.layer.borderColor = UIColor.LightGrey.cgColor
        //self.jbview.layer.borderWidth = 1
        self.jbview.layer.contents = UIImage.init(named: "shawcircle")?.cgImage
        self.jbview.layer.backgroundColor = UIColor.clear.cgColor
        
        self.refreshBtn.layer.contents = UIImage.init(named: "shawcircle")?.cgImage
        self.refreshBtn.layer.backgroundColor = UIColor.clear.cgColor
        self.refreshBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 5, 0)
        
        
        self.mapDetail?.tag = 0
        self.zoomValue = 17
        mapView.zoomLevel = self.mapZoom
        
        self.jbbtn.addTarget(self, action: #selector(jbClick(_:)), for: .touchUpInside)
        
        self.setupUI()
        //self.jbview.isUserInteractionEnabled = true
        //self.jbview.addGestureRecognizer(self.tap)
        //self.refreshBtn.addTarget(self, action: <#T##Selector#>, for: <#T##UIControlEvents#>)
    
        self.locationService = BMKLocationService.init()
       // self.locationService?.stopUserLocationService()
        self.locationService?.startUserLocationService()
        self.mapView.userTrackingMode = BMKUserTrackingModeFollow
        self.addNotificationObserve()
        self.mapDetail?.shadowEnable = true
        self.mapDetail?.snp.updateConstraints({ (make) in
            make.left.equalTo(self.view.snp.left).offset(10)
            make.right.equalTo(self.view.snp.right).offset(-10)
            make.height.greaterThanOrEqualTo(100)
            make.height.lessThanOrEqualTo(200)
            make.bottom.equalTo(self.view.snp.bottom).offset(100)
        })
        self.view.bringSubview(toFront: self.mapDetail!)
        
        NotificationCenter.default.addObserver(self, selector: #selector(xcRefresh(_:)), name: NSNotification.Name(rawValue: XCRefreshNotification), object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(xcRefresh(_:)), name: NSNotification.Name(rawValue: MGQDListNotification), object: nil)
        
    }
    
    @objc func xcRefresh(_ sender:Notification){
        print("刷新")
        /*guard let c = self.refresh else {
            return
        }
        c(false)*/
        if self.selectedProject != nil{
            self.refreshData()
        }
        
    }
    
    @objc func jbClick(_ sender:UIButton){
        print("警报")
        var vc = WarnController(nibName: "WarnController", bundle: nil)
        self.navigationController?.pushViewController(vc, animated: true)
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.3) {
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: WarnPersonNotification), object: (self.warnDwArray,self.warnQQArray))
        }
        
    }
    
    override func viewDidLayoutSubviews() {
        /*self.refreshBtn.shadowEnable = true
        self.refreshBtn.angle = self.refreshBtn.bounds.width / 2
        self.refreshBtn.layer.borderColor = UIColor.LightGrey.cgColor
        self.refreshBtn.layer.borderWidth = 1.5*/
        
        //self.warnNum.shadowEnable = true
        //self.warnNum.angle = self.refreshBtn.bounds.width / 2
        
        
        /*self.jbview.shadowEnable = true
        self.jbview.angle = self.jbview.bounds.width / 2
        self.jbview.layer.borderColor = UIColor.LightGrey.cgColor
        self.jbview.layer.borderWidth = 1.5*/
    }
    
    private func setupUI(){
        
        
        self.stepView.layer.cornerRadius = 5
        self.stepView.layer.masksToBounds = true
        self.stepView.layer.borderWidth = 1
        self.stepView.layer.borderColor = UIColor.init(red: 0.97, green: 0.97, blue: 0.97, alpha: 1).cgColor
        self.stepView.layer.shadowColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.2).cgColor
        self.view.bringSubview(toFront: self.stepView)
        self.view.bringSubview(toFront: self.refreshBtn)
        self.view.bringSubview(toFront: self.jbview)
        
    }
    
    
    
    
    

    private func addNotificationObserve(){
        let noficationName = Notification.Name.init(LCMainProjectNotification)
        
        NotificationCenter.default.addObserver(self, selector: #selector(getMWLocationData(notification:)), name: noficationName, object: nil)
    }
    //通知响应方法
    @objc func getMWLocationData(notification:Notification) {
        let userInfo = notification.userInfo as! [String:AnyObject]
        self.selectedProject = userInfo["project"] as? LCProjectListModel
        self.refreshData()
        /*mapView.removeOverlays(mapView.overlays)
        mapView.removeAnnotations(mapView.annotations)
        self.configDestination(selectedProject!)
        self.setupMWLocationData()*/
    }
    func refreshData(){
        mapView.removeOverlays(mapView.overlays)
        mapView.removeAnnotations(mapView.annotations)
        self.configDestination(selectedProject!)
        self.setupMWLocationData()
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    //请求民工的位置数据
    private func setupMWLocationData(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        SVProgressHUD.show(withStatus: "正在加载")
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.clear)
        LCAPiMainManager.request(.GetMWLotion(start: "0", limit: "10000", sql: "SignedResult >=-1", sqlParam: "{}", supplybaseid: (selectedProject?.MarketSupplyBaseID)!, AccountId: accountId)) { (result) in
            SVProgressHUD.dismiss()
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                self.itemArray.removeAll()
                self.warnDwArray.removeAll()
                self.warnQQArray.removeAll()
                print(jsonString)
                if let resultDic = jsonString["Result"] as? [String: AnyObject] {
                    if let itemDic = resultDic["Items"] as? [[String: Any]] {
                        
                        var dataArray = Mapper<MWCurrentLocationModel>().mapArray(JSONArray: itemDic)
                        dataArray.forEach({ (item) in
                            if item.SignedResult?.rawValue == -1 && item.IsAbsence ?? false {
                                self.warnQQArray.append(item)
                            } else if item.SignedResult?.rawValue == 0 && item.IsOnline == false{
                                self.warnDwArray.append(item)
                            }
                            if (item.SignedResult?.rawValue ?? -1) != -1{
                                self.itemArray.append(item)
                            }
                        })
                        print("\(self.itemArray.count)")
                        self.warnNum.text = String(self.warnQQArray.count+self.warnDwArray.count)
                    }
                }
                self.mapView.zoomLevel = self.mapZoom
                self.setupMWLocationAnnotations(self.itemArray)
              // self.setupLCMWStateData()
                return
            }else{
                
                //WWProgressHUD.error("数据请求失败")
            }
        }
    }
     //设置民工大头针
     private func setupMWLocationAnnotations(_ annotationArray : [MWCurrentLocationModel]){
        
        for index in 0..<annotationArray.count {
            let model : MWCurrentLocationModel = annotationArray[index]
            if model.SignedResult?.rawValue == 0{
                let locationData = model.Location
                let mwAnnotation = MWPointAnnotation.init()
                mwAnnotation.mwTag = 100+index
                mwAnnotation.title = ""
                self.mapView.selectAnnotation(mwAnnotation, animated: false)
                var mwCoor = CLLocationCoordinate2D.init()
                let lat = locationData?["Latitude"] as? String
                let lon = locationData?["Longitude"] as? String
                if lat != nil && lon != nil{
                    if let doubleLat = Double(lat ?? "0"),let doubleLon = Double(lon ?? "0"){
                        mwCoor.latitude = doubleLat
                        mwCoor.longitude = doubleLon
                        mwAnnotation.coordinate = mwCoor
                        mapView.addAnnotation(mwAnnotation)
                    }
                }
            }
            
            
        }
     }
    
    
    //设置工程位置
   private func configDestination(_ model: LCProjectListModel) {
    var totalX:Double = 0
    var totalY:Double = 0
    self.mapView.zoomLevel = self.mapZoom
    
    pointlist.removeAll()
    
    for index in (model.ProjectRangeBean?.ElectricFenceList)!{
        if index.Latitude == nil || index.Longitude == nil{
            continue
        }else{
            totalX += (index.Latitude as! NSString).doubleValue
            totalY += (index.Longitude as! NSString).doubleValue
            //var i = CLLocationCoordinate2D(latitude: (index.Latitude as! NSString).doubleValue, longitude: (index.Longitude as! NSString).doubleValue)
            pointlist.append(CLLocationCoordinate2D(latitude: (index.Latitude as! NSString).doubleValue, longitude: (index.Longitude as! NSString).doubleValue))
            //CLLocationCoordinate2D(latitude: index.Latitude, longitude: index.Longitude)
            //p.initialize(to: BMKMapPoint(x: (index.Latitude as! NSString).doubleValue, y: (index.Longitude as! NSString).doubleValue))
            //pointlist.append(BMKMapPoint(x: (index.Latitude as! NSString).doubleValue, y: (index.Longitude as! NSString).doubleValue))
        }
        
        //
    }
    guard pointlist.count > 0 else{
        ProjectMapPoint = [CLLocationCoordinate2D]()
        return
    }
    let centerX = totalX / Double(self.pointlist.count)
    let centerY = totalY / Double(self.pointlist.count)
    self.mapView.centerCoordinate = CLLocationCoordinate2D(latitude: centerX, longitude: centerY)
    ProjectMapPoint = self.pointlist
    NotificationCenter.default.post(name: NSNotification.Name.init(GuiJiPointList), object: self.pointlist, userInfo: nil)
    var polygon = BMKPolygon(coordinates: &pointlist, count: UInt(pointlist.count))
    self.mapView.add(polygon)
    
    
    
    
        /*if let lat = model.Latitude, let lon = model.Longitude {
             let doubuleLat = lat.doubleValue
            let doubleLon = lon.doubleValue
                //通过百度地图的view添加大头针
            self.companyAnnotation = BMKPointAnnotation()
                var coor = CLLocationCoordinate2D()
                coor.latitude = doubuleLat
                coor.longitude = doubleLon
            self.companyAnnotation?.coordinate = coor
            //self.mapView.addAnnotation( self.companyAnnotation)
                //将大头针放在地图中心
                self.mapView.centerCoordinate = coor
                //self.mapView.setCenter(coor, animated: false)
            
                //BMKPolygonContainsCoordinate(<#T##point: CLLocationCoordinate2D##CLLocationCoordinate2D#>, <#T##polygon: UnsafeMutablePointer<CLLocationCoordinate2D>!##UnsafeMutablePointer<CLLocationCoordinate2D>!#>, <#T##count: UInt##UInt#>)
                //var polygon = BMKPolygon(points: &pointlist, count: pointlist.count)
                //设置显示范围
                /*let aRadius = model.SignedRange ?? 100
                let circle = BMKCircle(center: coor, radius: aRadius)
                self.mapView.add(circle)*/
                
                
            
        }*/
    }
    
    
    
    
    //放大缩小功能
    @IBAction func addButtonClick(_ sender: Any) {
        if (zoomValue! > 3 || zoomValue! == 3 ) && (zoomValue! < 21){
            zoomValue! += 0.5
            mapView.zoomLevel = zoomValue!
        }
        
    }
    @IBAction func reduceButtonClick(_ sender: Any) {
        if (zoomValue! > 3 ) && (zoomValue! < 21 || zoomValue! == 21 ){
            zoomValue! -= 0.5
            mapView.zoomLevel = zoomValue!
        }
    }
    @IBAction func refresh(_ sender:UIButton){
        /*guard let c = self.refresh else {
            return
        }
        c(true)*/
        self.refreshData()
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: MDCQListNotification), object: nil)
    }
    
    
}



extension LCSceneViewController : BMKMapViewDelegate,BMKLocationServiceDelegate{
    func showMapDetail(){
        self.mapDetail?.snp.updateConstraints({ (make) in
            make.bottom.equalTo(self.view.snp.bottom).offset(-70)
        })
        UIView.animate(withDuration: 0.4, animations: {
            self.view.layoutIfNeeded()
        }) { (flag) in
            if flag{
                self.mapDetail?.tag = 1
            }
        }
    }
    func hideMapDetail(_ isshow:Bool = false){
        self.mapDetail?.snp.updateConstraints({ (make) in
            make.bottom.equalTo(self.view.snp.bottom).offset(100)
        })
        UIView.animate(withDuration: 0.4, animations: {
            self.view.layoutIfNeeded()
        }) { (flag) in
            if flag{
                self.mapDetail?.tag = 0
                guard isshow else{
                    return
                }
                self.showMapDetail()
            }
        }
    }
    
    @objc func turnToGj(_ sender:UIButton){
        var vc = WorkGuiJiControllerViewController(nibName: "WorkGuiJiControllerViewController", bundle: nil)
        //vc.MarketSupplyBaseID = self.MigrantWorkerID ?? ""
        vc.DemandBaseMigrantWorkerID = self.selectmodel?.ID ?? ""
        vc.LocateTime =  self.selectmodel?.Location?.object(forKey: "LocateTime") as? String ?? ""
        vc.MarketSupplyBaseID = self.selectedProject?.MarketSupplyBaseID
        vc.ProjectRange = ProjectMapPoint
        
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func mapView(_ mapView: BMKMapView!, didSelect view: BMKAnnotationView!) {
         print("didSelect\(view.tag)")
        var model = selectModelArray[view.tag]
        self.selectmodel = selectModelArray[view.tag]
        var headimg = (model.MigrantWorker?.object(forKey: "Photo") as! NSDictionary).object(forKey: "Path") as? String ?? ""
        var name = NSDictionary(dictionary: model.MigrantWorker?.object(forKey: "CompanyMG") as! NSDictionary).object(forKey: "CompanyName") as? String ?? ""
        var address = "",time = ""
        if (model.Location as! NSDictionary).object(forKey: "Address") != nil {
            address = (model.Location as! NSDictionary).object(forKey: "Address") as? String ?? ""
        }
        if (model.Location?.object(forKey: "LocateTime") != nil){
            time = model.Location?.object(forKey: "LocateTime") as? String ?? ""
        }
        
        if time.count > 20{
            var startindex = time.index(time.startIndex, offsetBy: 11)
            var endindex = time.index(startindex,offsetBy:5)
            time = time.substring(with: startindex..<endindex)
        }
        
        if headimg != nil{
            self.mapDetail?.headImg.kf.setImage(with: URL.init(string: (ImageUrlPrefix + headimg)), placeholder: UIImage(named: "scene_touxiang"), options: nil, progressBlock: nil, completionHandler: nil)
        }
        print("\(headimg)--\(name)--\(address)--\(time)")
        self.mapDetail?.name.text = name
        self.mapDetail?.addressview.text = address
        self.mapDetail?.timelabel.text = time
        self.mapDetail?.gjlabel.addTarget(self, action: #selector(turnToGj(_:)), for: .touchUpInside)
        
        
        self.setupSelectViewData(model, callBack: { (result) in
            if result == true {
                if self.workerModel?.LocateLossHours == 0 {
                    self.mapDetail?.jllabel.text = "无异常记录"
                }else{
                    let stateFloat = self.workerModel?.LocateLossHours
                    let stateStr = String(format: "%.2f", stateFloat!)
                    self.mapDetail?.jllabel.text = "中途失联" + stateStr + "小时"
                }
            }
        })
        
        
        
        
        
        if self.mapDetail?.tag == 0 {
            self.showMapDetail()
        }else{
            self.hideMapDetail(true)
        }
    }
    func mapView(_ mapView: BMKMapView!, onClickedMapPoi mapPoi: BMKMapPoi!) {
        print("onClickedMapPoi")
        self.hideMapDetail()
    }
    func mapView(_ mapView: BMKMapView!, onClickedMapBlank coordinate: CLLocationCoordinate2D) {
        print("onClickedMapBlank")
        self.hideMapDetail()
    }
    private func setupSelectViewData(_ selecModel: MWCurrentLocationModel,callBack:@escaping (Bool) ->Void){
        //WWProgressHUD.showWithStatus("数据正在载入中...")
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        guard let MarketSupplyBaseID = selectedProject?.MarketSupplyBaseID else{
            return
        }
        guard let DemandBaseMigrantWorkerID :String = selecModel.ID else{
            return
        }
        var time = dateToString(date: Date())
    LCAPiMainManager.request(.GetMWTrack(DemandBaseMigrantWorkerID: DemandBaseMigrantWorkerID, MarketSupplyBaseID: MarketSupplyBaseID, locateDate: time ?? "", IsShowDetail: true, AccountId: accountId), completion: { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
                let resultDic : NSDictionary = jsonString["Result"] as! NSDictionary
                let workerDic :NSDictionary = resultDic["MigrantWorker"] as! NSDictionary
                self.workerModel = Mapper<LCMWPersonInfo>().map(JSONObject: workerDic)!
                callBack(true)
                
                return 
            }else{
                callBack(false)
            }
        })
}
    func mapView(_ mapView: BMKMapView!, viewFor overlay: BMKOverlay!) -> BMKOverlayView! {
        /*if (overlay as? BMKCircle) != nil {
            let circleView = BMKCircleView(overlay: overlay)
            circleView?.fillColor = colorWith255RGBA(16, g: 142, b: 233, a: 0.2)
            circleView?.strokeColor = colorWith255RGBA(16, g: 142, b: 233, a: 1)
            circleView?.lineWidth = 1
            
            return circleView
        }*/
        if (overlay as? BMKPolygon) != nil{
            let view = BMKPolygonView(polygon: overlay as! BMKPolygon!)
            view?.fillColor = colorWith255RGBA(16, g: 142, b: 233, a: 0.1)
            view?.strokeColor = colorWith255RGBA(16, g: 142, b: 233, a: 0.8)
            view?.lineWidth = 1
            view?.lineDash = true
            return view
        }
        return UIView() as! BMKOverlayView
    }
    
    func mapView(_ mapView: BMKMapView!, viewFor annotation: BMKAnnotation!) -> BMKAnnotationView! {

        if(annotation as! BMKPointAnnotation) == companyAnnotation{
            let AnnotationViewID = "renameMark"
            var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: AnnotationViewID) as! BMKPinAnnotationView?
            if annotationView == nil {
                annotationView = BMKPinAnnotationView(annotation: annotation, reuseIdentifier: AnnotationViewID)
                annotationView?.image = UIImage(named: "企业位置")
                annotationView?.frame = CGRect(x: 0, y: 0, width: 30, height: 39)//大头针大小，根据图片宽高比等比配置
                
                annotationView?.annotation = annotation
                return annotationView
        }
        }
        if annotation.isKind(of: MWPointAnnotation.self){
            let mwAnnotation = annotation as! MWPointAnnotation
            let selectModel : MWCurrentLocationModel = self.itemArray[mwAnnotation.mwTag! - 100]
           // let stateModel : LCMWPersonInfo = self.workInforArray[mwAnnotation.mwTag! - 100]
            let dataDic : NSDictionary = selectModel.MigrantWorker!
            let companyDic = dataDic["CompanyMG"] as! NSDictionary
            
            let photoDic = dataDic["Photo"] as! NSDictionary
            let locationDic = selectModel.Location
        let mwAnnotationViewID = "mingong"
            
        var mwAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: mwAnnotationViewID) as! LCMWAnnotationView?
            if mwAnnotationView == nil {
                mwAnnotationView = LCMWAnnotationView(annotation: annotation, reuseIdentifier: mwAnnotationViewID)
            }
            
            if let imageUrl:String = photoDic["Path"] as? String {
                let mw_imageUrl = LC_IMAGE_URL + imageUrl
                let url:NSURL = NSURL(string: mw_imageUrl)!
                let imageData = NSData(contentsOf: url as URL)
                if let mwImage = UIImage(data: imageData! as Data, scale: 1.0){
                    mwAnnotationView?.image = mwImage;
                }
            }else{
                mwAnnotationView?.image = UIImage.init(named: "scene_touxiang")
            }
//            guard let imageUrl:String = photoDic["Path"] as? String else{
//                return
//            }
//            if let imageUrl:String = photoDic["Path"] as? String{
//
//            }
            
//            let mw_imageUrl = LC_IMAGE_URL + imageUrl
//            let url:NSURL = NSURL(string: mw_imageUrl)!
//            let imageData = NSData(contentsOf: url as URL)
//            let mwImage = UIImage(data: imageData! as Data, scale: 1.0)
//            mwAnnotationView?.image = mwImage;
           
            mwAnnotationView?.frame = CGRect(x: (mwAnnotationView?.frame.origin.x)!, y: (mwAnnotationView?.frame.origin.y)!, width: 30, height: 30)
            mwAnnotationView?.layer.cornerRadius = 15
            mwAnnotationView?.layer.masksToBounds = true
            mwAnnotationView?.layer.borderWidth = 2
            mwAnnotationView?.canShowCallout = false
            let workLat = locationDic!["Latitude"] as! String
            let workLon = locationDic!["Longitude"] as! String
            
            if selectModel.SignedResult!.rawValue == 0{
                
                
                
                
                if selectModel.IsOnline == true{
                    var isInOut = BMKPolygonContainsCoordinate(CLLocationCoordinate2D(latitude: (workLat as! NSString).doubleValue, longitude: (workLon as! NSString).doubleValue), &pointlist, UInt(pointlist.count))
                    if isInOut{
                        mwAnnotationView?.layer.borderColor = UIColor.green.cgColor
                    }else{
                        mwAnnotationView?.layer.borderColor = UIColor.red.cgColor
                    }
                    
                }else{
                    mwAnnotationView?.layer.borderColor = UIColor.lightGray.cgColor
                }
                
            }else if selectModel.SignedResult!.rawValue == 1{
                //mwAnnotationView?.layer.borderColor = UIColor.lightGray.cgColor
                return nil
            }else{
                return nil
            }
            
            
            /*self.comfirmMWIsRange(workLat, workLon, callBack: { (result) in
                if result == true{
                    if selectModel.IsOnline == true{
                        mwAnnotationView?.layer.borderColor = UIColor.green.cgColor
                    }else{
                        mwAnnotationView?.layer.borderColor = UIColor.lightGray.cgColor
                    }
                }else{
                   mwAnnotationView?.layer.borderColor = UIColor.red.cgColor
                }
            })*/
            //mwAnnotationView
            
            self.selectModelArray.append(selectModel)
            mwAnnotationView?.tag = self.selectModelArray.count - 1

            /*self.setupSelectViewData(selectModel, callBack: { (result) in
                if result == true {
                    let callView = LCCalloutView(frame: CGRect(x: 0, y: 0, width: 220, height: 160))
                    callView.nameLabel.text = self.workerModel?.Name
                    callView.addressLabel.text = locationDic!["Address"] as? String
                    if self.workerModel?.LocateLossHours == 0 {
                       callView.stateLabel.text = "状态良好"
                    }else{
                        let stateFloat = self.workerModel?.LocateLossHours
                        let stateStr = String(format: "%.2f", stateFloat!)
                        callView.stateLabel.text = "中途失联" + stateStr + "小时"
                    }
                    callView.checkButton.tag = mwAnnotation.mwTag! - 100
                    callView.checkButton.addTarget(self, action: #selector(self.trackCheckClick(_:)), for: .touchUpInside)
                    
                    let popView = BMKActionPaopaoView(customView: callView)
                    mwAnnotationView?.paopaoView = nil
                    mwAnnotationView?.paopaoView = popView
                }
            })*/
        return mwAnnotationView
        }
        return nil
    }
    @objc fileprivate func trackCheckClick(_ checkButton : UIButton){
        let checkModel : MWCurrentLocationModel = self.itemArray[checkButton.tag]
       let trackView = LCCheckTrackViewController(nibName: "LCCheckTrackViewController", bundle: nil)
       trackView.currentProject = self.selectedProject
       trackView.personInformation = checkModel
       self.navigationController?.pushViewController(trackView, animated: true)
    }
    func mapViewDidFinishLoading(_ mapView: BMKMapView!) {
        
    }
    func mapView(_ mapView: BMKMapView!, didAddAnnotationViews views: [Any]!) {
        
    }
    func mapViewDidFinishRendering(_ mapView: BMKMapView!) {
        WWProgressHUD.dismiss()
    }
    
    
    fileprivate func comfirmMWIsRange(_ latide:NSString,_ lontide:NSString,callBack:@escaping (Bool) ->Void){
        let proLatitude = selectedProject!.Latitude ?? NSString.init(string: "0")
        let proLonDouble = selectedProject!.Longitude ?? NSString.init(string: "0")
        var recordLatDouble = latide.doubleValue ?? 0
        var recordLonDouble = lontide.doubleValue ?? 0
        var companyLatDouble = proLatitude.doubleValue ?? 0
        var companylonDouble = proLonDouble.doubleValue ?? 0
            let recordCoor = CLLocationCoordinate2D(latitude: recordLatDouble, longitude: recordLonDouble)
            let companyCoor = CLLocationCoordinate2D(latitude: companyLatDouble, longitude: companylonDouble)
            let point1 = BMKMapPointForCoordinate(companyCoor)
            let point2 = BMKMapPointForCoordinate(recordCoor)
            let distance = BMKMetersBetweenMapPoints(point1, point2)
            
            self.inRange = (self.selectedProject?.SignedRange)! - distance
            if self.inRange! > Double(0) || self.inRange == 0{
                callBack(true)
            }else{
                callBack(false)
            }
        //}
    }
}
